const express = require("express");
const router = express.Router();
const userHandler = require("../routes_handle/user");
const { CODE, Response } = require("../utils/response");
const jwt = require("../utils/jwt");

// 用户注册
router.post("/user/register", async (req, res, next) => {
  try {
    const result = await userHandler.registerUser(req.body);
    res.status(CODE.SUCCESS).json(Response.success(result, "注册成功"));
  } catch (err) {
    next(err);
  }
});

// 用户登录
router.post("/user/login", async (req, res, next) => {
  try {
    const result = await userHandler.loginUser({
      ...req.body,
      deviceInfo: req.headers["user-agent"],
    });
    res.status(CODE.SUCCESS).json(Response.success(result, "登录成功"));
  } catch (err) {
    next(err);
  }
});

// 检查登录状态
router.get("/user/auth/check", async (req, res, next) => {
  try {
    const result = await userHandler.checkAuthStatus(
      req.query.FUsername,
      req.query.FPassword
    );
    res.status(CODE.SUCCESS).json(Response.success(result));
  } catch (err) {
    next(err);
  }
});

// 用户注销
router.post("/user/logout", async (req, res, next) => {
  try {
    await userHandler.logoutUser(req.body.userId, req.body.tokenId);
    res.status(CODE.SUCCESS).json(Response.success(null, "注销成功"));
  } catch (err) {
    next(err);
  }
});

// 获取当前用户信息
router.get("/user/info", async (req, res, next) => {
  try {
    const result = await userHandler.getUserInfo(req.body.userId);
    res.status(CODE.SUCCESS).json(Response.success(result));
  } catch (err) {
    next(err);
  }
});

// 刷新Token
router.post("/user/refresh", async (req, res, next) => {
  try {
    const { refresh_token } = req.body;
    if (!refresh_token) {
      return res
        .status(CODE.BAD_REQUEST)
        .json(Response.error("Refresh token required"));
    }

    const result = await jwt.refreshAccessToken(refresh_token);
    res.status(CODE.SUCCESS).json(
      Response.success({
        access_token: result.accessToken,
        refresh_token: result.refreshToken,
        tokenId: result.tokenId,
      })
    );
  } catch (err) {
    next({ status: CODE.FORBIDDEN, message: err.message });
  }
});

module.exports = router;